package com.cc.order;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.Customizer;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.netflix.hystrix.HystrixCircuitBreakerFactory;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableHystrix  /*启动Hystrix断路器*/
@EnableFeignClients(basePackages ="com.cc.order.feign") /*启动feign 去掉restTemplate远程调用*/
@EnableDiscoveryClient
public class OrderServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(OrderServiceApplication.class, args);
    }

    /**
     * 向Spring容器中定义RestTemplate对象
     * @return
     */
    /*负载均衡：当我们调用一个远程服务，而这个远程服务有多个节点，需要一个决策来确定具体调用哪个节点节点提供服务*/
    @LoadBalanced
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

//    @Bean
//    public Customizer<HystrixCircuitBreakerFactory> customizer() {
//        return factory -> factory.configure(builder -> builder.commandProperties(
//                HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(2000)), "foo", "bar");
//    }

    @Bean
    public Customizer<HystrixCircuitBreakerFactory> defaultConfig() {
        return factory -> factory.configureDefault(id -> HystrixCommand.Setter
                .withGroupKey(HystrixCommandGroupKey.Factory.asKey(id))
                .andCommandPropertiesDefaults(HystrixCommandProperties.Setter()
                        //服务降级超时时间
                        .withExecutionTimeoutInMilliseconds(2000)
//                        // 熔断的请求阀值
//                        .withCircuitBreakerRequestVolumeThreshold(3)
//                        //阀值的比例
//                        .withCircuitBreakerErrorThresholdPercentage(50)
//                        //滑动窗口时间：metrics.rollingStats.timeInMilliseconds
//                        .withMetricsRollingStatisticalWindowInMilliseconds(3000)
//                        //
//                        .withCircuitBreakerSleepWindowInMilliseconds(3000)
                ));
    }
}
